#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <String.h>
#include <ESP8266HTTPUpdateServer.h>
#include "web_server.h"

static ESP8266WebServer server(80);
static DNSServer dnsServer;
static webserver_cabllback * ws_cb;
// 创建 ESP8266HTTPUpdateServer 实例
static ESP8266HTTPUpdateServer httpUpdater; // 用于处理 OTA 升级, 接管/update 路由

const char * text_response_header = "text/plain; charset=UTF-8";

// 处理根路径的请求，显示配置页面
static void handleRoot() {
    String root_page = "<html><head><meta charset='UTF-8'></head><body>";
    root_page += "<h1>设备控制中心</h1>";
    // 配网按钮
    root_page += "<form action='/wifi_config' method='get'>";
    root_page += "<input type='submit' value='Wi-Fi 配网'>";
    root_page += "</form>";
    // LED 控制按钮
    root_page += "<form action='/led_config' method='get'>";
    root_page += "<input type='submit' value='LED 控制'>";
    root_page += "</form>";
    // 红外控制按钮，假设红外控制页面路径为 /ir
    root_page += "<form action='/ir_config' method='get'>";
    root_page += "<input type='submit' value='红外控制'>";
    root_page += "</form>";
    // 重置配置按钮
    root_page += "<form action='/reset_config' method='get'>";
    root_page += "<input type='submit' value='重置配置'>";
    root_page += "</form>";
    // OTA 升级按钮
    root_page += "<form action='/ota_config' method='get'>";
    root_page += "<input type='submit' value='OTA 升级'>";
    root_page += "</form>";
    root_page += "</body></html>";
    server.send(200, "text/html", root_page);
}

// 处理 OTA 升级页面请求
static void handleOTAConfig_Page() {
    String ota_page = "<html><head><meta charset='UTF-8'></head><body>";
    ota_page += "<h1>OTA 升级</h1>";
    ota_page += "<form action='/update' method='post' enctype='multipart/form-data'>";
    ota_page += "<input type='file' name='update'><br>";
    ota_page += "<input type='submit' value='上传并升级'>";
    ota_page += "</form>";
    ota_page += "<a href='/'>返回首页</a>";
    ota_page += "</body></html>";
    server.send(200, "text/html", ota_page);
}

// 处理根路径的请求，显示配置页面
static void handleWifiConfig_Page() {
    String wifi_config_page = "<html><head><meta charset='UTF-8'></head><body>";
    wifi_config_page += "<h1>Wi-Fi 配置</h1>";
    wifi_config_page += "<form action='/wifi' method='get'>";
    wifi_config_page += "SSID: <input type='text' name='ssid'><br>";
    wifi_config_page += "密码: <input type='password' name='password'><br>";
    wifi_config_page += "<input type='submit' value='连接'>";
    wifi_config_page += "</form>";
    wifi_config_page += "</body></html>";
    server.send(200, "text/html", wifi_config_page);

}

// 处理连接 Wi-Fi 的请求
static void handleWifi() {
    if (server.hasArg("ssid") && server.hasArg("password")) {
        String ssid = server.arg("ssid");
        String password = server.arg("password");
        if (ws_cb && ws_cb->wc_cb) {
            ws_cb->wc_cb(ssid, password);
        }
        server.send(200, text_response_header, "Wi-Fi 配置已接收，正在尝试连接...");
    } else {
        server.send(400, text_response_header, "缺少必要参数");
    }
}

// 处理连接 Wi-Fi 的请求
static void handleLed_Page() {
    String led_page = "<html><head><meta charset='UTF-8'></head><body>";
    led_page += "<h1>LED 控制</h1>";
    led_page += "<form action='/led' method='get'>";
    led_page += "LED 引脚: <input type='number' name='led' value='12'><br>";
    led_page += "状态: <select name='status'>";
    led_page += "<option value='true'>开</option>";
    led_page += "<option value='false'>关</option>";
    led_page += "</select><br>";
    led_page += "<input type='submit' value='设置 LED'>";
    led_page += "</form>";
    led_page += "</body></html>";
    server.send(200, "text/html", led_page);
}

static void handleLed() {
    if (server.hasArg("led") && server.hasArg("status")) {
        int led = server.arg("led").toInt();
        bool status = server.arg("status") == "true" ? true : false;
        if (ws_cb && ws_cb->led_cb) {
            ws_cb->led_cb(led, status);
        }
        server.send(200, text_response_header, "正在设置led...");
    } else {
        server.send(400, text_response_header, "缺少必要参数");
    }
}

// 处理红外控制页面请求
static void handleIR_Page() {
    String ir_page = "<html><head><meta charset='UTF-8'></head><body>";
    ir_page += "<h1>红外控制</h1>";
    ir_page += "<form action='/ir' method='get'>";
    ir_page += "红外命令: <input type='text' name='command'><br>";
    ir_page += "<input type='submit' value='发送命令'>";
    ir_page += "</form>";
    ir_page += "</body></html>";
    server.send(200, "text/html", ir_page);
}

// 处理红外控制页面请求
static void handleIR() {
}

// 处理重置配置页面请求
static void handleReset_Page() {
    String reset_page = "<html><head><meta charset='UTF-8'></head><body>";
    reset_page += "<h1>重置配置</h1>";
    reset_page += "<form action='/reset' method='post'>";
    reset_page += "<input type='submit' value='确认重置 Wi-Fi 配置'>";
    reset_page += "</form>";
    reset_page += "<a href='/'>返回首页</a>";
    reset_page += "</body></html>";
    server.send(200, "text/html", reset_page);
}

// 处理重置配置请求
static void handleReset() {
    if (ws_cb && ws_cb->reset_cb) {
        ws_cb->reset_cb();
    }
    server.send(200, text_response_header, "Wi-Fi 配置已重置，请重新配置。");
}

// Setup Web server
void setupWebServer(webserver_cabllback * _ws_cb){
    ws_cb = _ws_cb;
    // 初始化 OTA 服务器
    httpUpdater.setup(&server);

    // dnsServer.start(53, "*", WiFi.softAPIP());
    server.on("/", handleRoot);

    server.on("/wifi_config", handleWifiConfig_Page);
    server.on("/wifi", handleWifi);

    server.on("/led_config", handleLed_Page);
    server.on("/led", handleLed);

    server.on("/ir_config", handleIR_Page);
    server.on("/ir", handleIR);

    server.on("/reset_config", handleReset_Page);
    server.on("/reset", handleReset);

    // 添加 OTA 相关路由
    server.on("/ota_config", handleOTAConfig_Page);

    server.onNotFound([]()
        { server.send(404, text_response_header, "404: Not found"); });
    server.begin();
}

void handleServer() {
    server.handleClient();
    dnsServer.processNextRequest();
}

webserver_opt_t webserver_opt = {
    .init = setupWebServer,
    .handle = handleServer
};